
const ctxutil = require('@ym_interaction/ctx_util');

exports.main = async (ctx) => {
  await ctxutil.apply(ctx);
  const { mongo } = ctx.mfutil.db;
  try {
    const result = await mongo.find('test',{},{projection:{'_id':1}});
    return await ctx.mfutil.common.basicode(0, result);
  } catch (e) {
    return await ctx.mfutil.common.basicode(e.code || 8000, e);
  }

};

// 拉取用户的订单信息
exports.getTrade = async (ctx) => {
  const { cloud, openId } = ctx;
  try {
    let result = await cloud.topApi.invoke({
      api: "taobao.open.trades.sold.get",
      autoSession: true,
      data: {
        fields: "tid,type,status,payment,orders,rx_audit_status,buyer_nick",
        buyer_open_id: openId,
        page_no: 1,
        page_size: 100,
      },
    });
    return result;
  } catch (error) {
    return {
      success: false,
      data: {},
      errorCode: "5000",
      errorMessage: JSON.stringify(error),
    };
  }
};

//拉取买家单笔交易信息
exports.getTradeByTid = async (ctx) => {
  try {
    let result = await cloud.topApi.invoke({
      api: "taobao.open.trade.get",
      autoSession: true,
      data: {
        fields: "tid,type,status,payment,orders,buyer_nick",
        tid: ctx.data.tid
      },
    });
    return result;
  } catch (error) {
    return {
      success: false,
      data: {},
      errorCode: "5000",
      errorMessage: JSON.stringify(error),
    };
  }
};



exports.shorturl = async (ctx) => {
  let { data: { name, type = null, tile_id = null, channel = null }, cloud } = ctx;
  try {
    let url = `https://m.duanqu.com?_ariver_appid=3000000028855844&query=params=${type},${tile_id},${channel}`
    console.log("xxxxxxxxxurlurlurlurlxxxxxxxxxx",url)
    const result = await cloud.topApi.invoke({
      api: 'taobao.miniapp.shorturl.create',
      data: {
        'miniapp_url': url
      },
      autoSession: true, //如果是云应用中调用，没有这个字段，需要手动传入商家授权获取的sessionkey去调用接口  
    });
    const short_url = result.result.model.short_url
    return short_url
    let sql = `INSERT INTO short (gmt_create,gmt_modified,name,type,tile_id,channel,short_url) VALUES(now(),now(),?,?,?,?,?);`

    let short = await cloud.dataspace.executeSql(sql, [name, type, tile_id,channel, short_url])
    if (short && short.affectedRows && short.insertId) {
      return { success: true, insertId: short.insertId }
    } else {
      return { success: false, msg: "添加失败" }
    }

  } catch (e) { return { success: false, msg: e } }
};